package com.subway.babynote.syncservice;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import weibo4andriod.http.AccessToken;

import android.content.Context;
import android.database.sqlite.SQLiteException;
import android.util.Log;

import com.subway.babynote.NotedbHelper;
import com.subway.babynote.db.TableInfoList;
import com.subway.babynote.db.logging;
import com.subway.babynote.db.query_contact;
import com.subway.babynote.db.query_feed;
import com.subway.babynote.db.query_feedback;
import com.subway.babynote.db.query_food_default;
import com.subway.babynote.db.query_food_ux;
import com.subway.babynote.db.query_foods;
import com.subway.babynote.db.query_h_avg;
import com.subway.babynote.db.query_h_default;
import com.subway.babynote.db.query_h_ux;
import com.subway.babynote.db.query_huser;
import com.subway.babynote.db.query_last_avg;
import com.subway.babynote.db.query_loadinfo;
import com.subway.babynote.db.query_tip;
import com.subway.babynote.db.query_users;
import com.subway.babynote.db.query_w_default;
import com.subway.babynote.db.query_w_ux;
import com.subway.babynote.db.query_weibo;
import com.subway.babynote.db.query_wuser;
import com.subway.babynote.syncdata.ClientDataRecord;
import com.subway.babynote.syncdata.ClientDataRecord.clientFeedRecord;
import com.subway.babynote.syncdata.ClientDataRecord.contactRecord;
import com.subway.babynote.syncdata.ClientDataRecord.feedRecord;
import com.subway.babynote.syncdata.ClientDataRecord.foodsRecord;
import com.subway.babynote.syncdata.ClientDataRecord.hwAvgRecord;
import com.subway.babynote.syncdata.ClientDataRecord.last_avgRecord;
import com.subway.babynote.syncdata.ClientDataRecord.loadinfoRecord;
import com.subway.babynote.syncdata.ClientDataRecord.tipRecord;
import com.subway.babynote.syncdata.ClientDataRecord.usersRecord;
import com.subway.babynote.syncdata.ClientDataRecord.uxRecord;
import com.subway.babynote.syncdata.ClientDataRecord.weiboRecord;
import com.subway.babynote.syncdata.ClientDataRecordBase;
import com.subway.babynote.syncdata.PostParam;
import com.subway.babynote.syncdata.StringUtil;
import com.subway.babynote.syncdata.errMessage;
import com.subway.babynote.syncdata.pWrapper;
import com.subway.babynote.syncdata.safeobj;
import com.subway.babynote.syncdata.ClientDataRecord.tsType;
import com.subway.babynote.syncdata.tableName;

import com.subway.babynote.syncdata.pWrapper.MinMax;
import com.subway.babynote.syncdata.wrapper;
import com.subway.babynote.syncservice.taskList.tsPair;

public class taskHelp_impl extends taskHelper {

	localdbhandler ldb = null;
	safeobj<ClientDataRecord.tsType> tscache = new safeobj<ClientDataRecord.tsType>();
	httpUtil hu = null;
	RunnableTask r = null;
	private boolean is_init = false;
	static final String uri = "datasync";
	public boolean init(Context context, RunnableTask rt)
	{
		boolean bret = true;
		try
		{
			if(!is_init)
			{
				is_init = true;
				r = rt;
				ldb = new localdbhandler(context);
				bret = ldb.init();
				if(bret)
				{
					hu = new httpUtil();
					bret = hu.init();				
				}
			}
				
			return bret;
			
		}
		catch(Exception e)
		{
			return false;
		}
	}
	
	public void finalize()
	{
		ldb.finalize();
	}
	
	public ClientDataRecord.tsType getts ()
	{
		return tscache.get();
	}
	
	List<NameValuePair> newparams()
	{
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		return params;
	}
	
	private boolean needadd(ClientDataRecord.ts sts, ClientDataRecord.ts clientts)
	{
		if(sts.ts < clientts.ts)
			return true;
		else
			return false;
	}
	private ClientDataRecord.ts get_ts(ClientDataRecord.list_ClientDataRecord t, int client_id)
	{
		ClientDataRecord.ts c = null;
		Iterator<ClientDataRecordBase> it= t.list.iterator();
		while(it.hasNext())
		{
			ClientDataRecordBase cdrb = it.next();
			ClientDataRecord.ts a = (ClientDataRecord.ts) cdrb;
			if(a.client_id == client_id || a.client_id == -1)
				c = a;
		}
		return c;
	}
	
	private boolean getLocalData(String tablename,int client_id,ClientDataRecord.tsType sts, ClientDataRecord.tsType cts, wrapper<ClientDataRecord.ts> serverts)
	{
		ClientDataRecordBase c = null;
		c = cts.c.map.get(tablename);
		ClientDataRecordBase s = null;
		s = sts.c.map.get(tablename);
		
		ClientDataRecord.ts ct = null;
		ClientDataRecord.ts st = null;
		
		if(c == null || s == null)
			return false;
		
		if(c.get_type() == ClientDataRecordBase.ClientDataRecord_TYPE.list)
		{
			ClientDataRecord.list_ClientDataRecord lc = (ClientDataRecord.list_ClientDataRecord) c;
			ct = this.get_ts(lc, client_id);
			ClientDataRecord.list_ClientDataRecord ls = (ClientDataRecord.list_ClientDataRecord) s;
			st = this.get_ts(ls, client_id);
		}
		else
		{
			ct = (ClientDataRecord.ts) c;
			st = (ClientDataRecord.ts) s;
		}
		serverts.set(st);
		
		if(ct !=null && st != null)
			return this.needadd(st, ct);
		else if(st == null && ct != null)
			return true;
		else 
			return false;	
		
	}
	
	public boolean haswork()
	{
		int iret = 0;
		String tn = tableName.t_ts;
		
		ClientDataRecordBase cdrb = ldb.getts();
		if(cdrb == null)
			iret = -1;
		ClientDataRecord.tsType cts = (ClientDataRecord.tsType) cdrb;
		
		cdrb = this.getts();
		if(cdrb != null)
		{
			ClientDataRecord.tsType sts = (ClientDataRecord.tsType) cdrb;
			int client_id = uai_Sing.get_uai().client_id;
			tn = tableName.t_feedbacks;
			boolean bret = false;
			wrapper<ClientDataRecord.ts> cs = new wrapper<ClientDataRecord.ts>(null);
			bret = this.getLocalData(tn, client_id, sts, cts, cs);
			if(bret)
				return bret;
			
			tn = tableName.t_feeds;
			cs.set(null);
			bret = false;
			bret = this.getLocalData(tn, client_id, sts, cts, cs);
			if(bret)
				return bret;
			
			tn = tableName.t_huser;
			cs.set(null);
			bret = false;
			bret = this.getLocalData(tn, client_id, sts, cts, cs);
			if(bret)
				return bret;
			
			tn = tableName.t_users;
			cs.set(null);
			bret = false;
			bret = this.getLocalData(tn, client_id, sts, cts, cs);
			if(bret)
				return bret;
			
			tn = tableName.t_weibo;
			cs.set(null);
			bret = false;
			bret = this.getLocalData(tn, client_id, sts, cts, cs);
			if(bret)
				return bret;
			
			tn = tableName.t_wuser;
			cs.set(null);
			bret = false;
			bret = this.getLocalData(tn, client_id, sts, cts, cs);
			if(bret)
				return bret;
			return bret;
		}
		else
			return true;
	}
	
	public int addtoServer()
	{
		int iret = 0;
		String tn = tableName.t_ts;
		ClientDataRecord.map_ClientDataRecord ret = new ClientDataRecord.map_ClientDataRecord();
		ClientDataRecordBase cdrb = ldb.getts();
		if(cdrb == null)
			iret = -1;
		ClientDataRecord.tsType cts = (ClientDataRecord.tsType) cdrb;
		if(iret >=0)
			ret.map.put(tableName.t_ts, cdrb);
		if(iret >= 0 )
			ret.map.put(tableName.t_uai,uai_Sing.get_uai());
		cdrb = this.getts();
		if(cdrb != null)
		{
			ClientDataRecord.tsType sts = (ClientDataRecord.tsType) cdrb;
			int client_id = uai_Sing.get_uai().client_id;
			tn = tableName.t_feedbacks;
			boolean bret = false;
			wrapper<ClientDataRecord.ts> cs = new wrapper<ClientDataRecord.ts>(null);
			bret = this.getLocalData(tn, client_id, sts, cts, cs);
			if(bret)
			{
				ClientDataRecord.ts t = cs.get();
				int server_ts = t==null?0:t.ts;
				cdrb = ldb.getFeedback(server_ts);
				if(cdrb != null)
					ret.map.put(tn, cdrb);
			}
			
			
			tn = tableName.t_feeds;
			cs.set(null);
			bret = false;
			bret = this.getLocalData(tn, client_id, sts, cts, cs);
			if(bret)
			{
				ClientDataRecord.ts t = cs.get();
				int server_ts = t==null?0:t.ts;
				cdrb = ldb.getFeedRecord(server_ts, client_id);
				if(cdrb != null)
					ret.map.put(tn, cdrb);
			}
			
			tn = tableName.t_huser;
			cs.set(null);
			bret = false;
			bret = this.getLocalData(tn, client_id, sts, cts, cs);
			if(bret)
			{
				ClientDataRecord.ts t = cs.get();
				int server_ts = t==null?0:t.ts;
				cdrb = ldb.gethuserRecord(server_ts);
				if(cdrb != null)
					ret.map.put(tn, cdrb);
			}
			
			tn = tableName.t_users;
			cs.set(null);
			bret = false;
			bret = this.getLocalData(tn, client_id, sts, cts, cs);
			if(bret)
			{
				ClientDataRecord.ts t = cs.get();
				int server_ts = t==null?0:t.ts;
				cdrb = ldb.get_userRecord();
				if(cdrb != null)
					ret.map.put(tn, cdrb);
			}
			
			tn = tableName.t_weibo;
			cs.set(null);
			bret = false;
			bret = this.getLocalData(tn, client_id, sts, cts, cs);
			if(bret)
			{
				ClientDataRecord.ts t = cs.get();
				int server_ts = t==null?0:t.ts;
				cdrb = ldb.getweiboRecord(server_ts);
				if(cdrb != null)
					ret.map.put(tn, cdrb);
			}
			
			tn = tableName.t_wuser;
			cs.set(null);
			bret = false;
			bret = this.getLocalData(tn, client_id, sts, cts, cs);
			if(bret)
			{
				ClientDataRecord.ts t = cs.get();
				int server_ts = t==null?0:t.ts;
				cdrb = ldb.getwuserRecord(server_ts);
				if(cdrb != null)
					ret.map.put(tn, cdrb);
			}
		}
		wrapper<ClientDataRecordBase> ret_crb = new wrapper<ClientDataRecordBase>(null);
		iret = this.addRecordbase(this.uri, ret, ret_crb);
		if(iret >= 0)
		{
			iret = this.addtolocaldb(ret_crb.get());
		}
		
		return iret;
			
	}
	
	private int addtolocaldb(ClientDataRecordBase crb)
	{
		int iret = (crb == null ? -1 : 0);
		if(iret < 0)
			return iret;
		ClientDataRecord.map_ClientDataRecord combo = (ClientDataRecord.map_ClientDataRecord) crb;
		Set<String> st = combo.map.keySet();
		Iterator<String> it = st.iterator();
		while(it.hasNext())
		{
			String key = it.next();
			ClientDataRecordBase cdrb = combo.map.get(key);
			iret = this.addtolocaldb(key, cdrb);
			logging.info(key, StringUtil.int2str(iret));
		}
		
		return iret;
	}
	
	private int addtolocaldb(String tablename,ClientDataRecordBase crb)
	{
		int iret = 0;
		if(tablename.equals(tableName.t_avg_height))
			iret = ldb.insertHeight_AVG(crb);
		else if(tablename.equals(tableName.t_ourcontact))
			iret = ldb.insertContact(crb);
		else if(tablename.equals(tableName.t_feeds))
			iret = ldb.insertFeeds(crb);
		else if(tablename.equals(tableName.t_feedbacks))
		{
			
		}
		else if(tablename.equals(tableName.t_food_default))
			iret = ldb.insert_food_default(crb);
		else if(tablename.equals(tableName.t_food_ux))
			iret = ldb.insert_food_ux(crb);
		else if(tablename.equals(tableName.t_foods))
			iret = ldb.insertFoods(crb);
		else if(tablename.equals(tableName.t_h_default))
			iret = ldb.insert_h_default(crb);
		else if(tablename.equals(tableName.t_h_ux))
			iret = ldb.insert_h_ux(crb);
		else if(tablename.equals(tableName.t_huser))
		{
			
		}
		else if(tablename.equals(tableName.t_local_avg))
			iret = ldb.insertLastAverage(crb);
		else if(tablename.equals(tableName.t_loadinfo))
			iret = ldb.insertLoadinfo(crb);
		else if(tablename.equals(tableName.t_tips))
			iret = ldb.insertTip(crb);
		else if(tablename.equals(tableName.t_users))
		{
			ClientDataRecord.usersRecord ur = (ClientDataRecord.usersRecord) crb;
			iret = ldb.insertUser(ur);
			if(iret >=0)
			{
				boolean bret = this.r.hang_wake();
				logging.info("addtolocaldb ", StringUtil.bool2str(bret));
			}
		}
		else if(tablename.equals(tableName.t_w_default))
			iret = ldb.insert_w_default(crb);
		else if(tablename.equals(tableName.t_w_ux))
			iret = ldb.insert_w_ux(crb);
		else if(tablename.equals(tableName.t_weibo))
			iret = ldb.insertWeibo(crb);
		else if(tablename.equals(tableName.t_wuser))
		{
			
		}
		else if(tablename.equals(tableName.t_ts))
		{
			ClientDataRecord.tsType tt = (ClientDataRecord.tsType) crb;
			this.tscache.set(tt);
		}
		else if(tablename.equals(tableName.t_uai))
		{
			ClientDataRecord.user_auth_info ua = (ClientDataRecord.user_auth_info) crb;
			String imei = uai_Sing.get_uai().imei;
			String imsi = uai_Sing.get_uai().imsi;
			uai_Sing.init(ua.id, imsi, imei, ua.client_id, ua.isuser);
			iret = ldb.update_client_id(ua.client_id);
		}
		return iret;
	}
	

	@Override
	public int loginUser(String username, String passwd) {
		// TODO Auto-generated method stub
		int iret= -1;
		boolean bret = false;
		List<NameValuePair> params = this.newparams();
		ClientDataRecord.usersRecord ur = new ClientDataRecord.usersRecord();
		ClientDataRecord.user_auth_info uai = new ClientDataRecord.user_auth_info();
		wrapper<JSONObject> pjson_resp = new wrapper<JSONObject>(null);		
		httpUtil htu = new httpUtil();
		bret = htu.init_mainthread();
		if(bret)
		{
			uai.imei = HardwareHelper.getDM().getIMEI();
			uai.imsi = HardwareHelper.getDM().getIMSI();
			ur.email = username;
			ur.passwd = passwd;
			
			params.add(new BasicNameValuePair(PostParam.p,ur.toJSON().toString()));
			params.add(new BasicNameValuePair(PostParam.user_auth_info_Param.record,uai.toJSON().toString()));
			bret = htu.send(syncapi.operation_type.loginUser.urlpattern, 
					params, 
					pjson_resp);			
		}
		if(bret)
		{
			iret = this.deal_realtime_request(pjson_resp.get());	
		}
		else
			iret = errMessage.err_sendtoservlet.errcode;		
		return iret;
	}
	
	private int deal_realtime_request(JSONObject jsono)
	{
		int iret = -1;
		try {
			if(jsono == null)
			{
				iret = -1;
				return iret;
			}
			else
				iret = 0;
			
			ClientDataRecordBase ret = ClientDataRecordBase.fromJSON(jsono);
			if(ret == null)
				iret = -1;
			else
				iret = 0;
			if(iret >= 0)
			{
				ClientDataRecord.map_ClientDataRecord resp = (ClientDataRecord.map_ClientDataRecord) ret;
				if( resp.map.containsKey(tableName.t_return))
				{
					ClientDataRecordBase cdrb = resp.map.get(tableName.t_return);
					ClientDataRecord.returnValue r = (ClientDataRecord.returnValue) cdrb;
					iret = r.errcode;
				}
			}
			if(iret>=0)				
			{						
				iret = this.addtolocaldb(ret);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			iret = errMessage.err_json.errcode;
		}		
		return iret;
	}

	@Override
	public int regUser(ClientDataRecord.usersRecord ur) {
		// TODO Auto-generated method stub
		int iret= -1;
		boolean bret = false;
		List<NameValuePair> params = this.newparams();
		ClientDataRecord.user_auth_info uai = new ClientDataRecord.user_auth_info();
		wrapper<JSONObject> pjson_resp = new wrapper<JSONObject>(null);		
		httpUtil htu = new httpUtil();
		bret = htu.init_mainthread();
		if(bret)
		{
			ClientDataRecordBase cdrb = ldb.get_userRecord();
			if(cdrb != null)
			{
				ClientDataRecord.usersRecord ur_old = (ClientDataRecord.usersRecord) cdrb;
				ur.birth = ur_old.birth;
				ur.first_reg_time =  StringUtil.now();
				ur.first_use_time = ur_old.first_use_time;
				ur.gender  = ur_old.gender;
				ur.isuser = true;
				ur.ts = StringUtil.now();
				ur.user_id = ur_old.user_id;
			}			
			uai.imei = HardwareHelper.getDM().getIMEI();
			uai.imsi = HardwareHelper.getDM().getIMSI();		
			
			params.add(new BasicNameValuePair(PostParam.p,ur.toJSON().toString()));
			params.add(new BasicNameValuePair(PostParam.user_auth_info_Param.record,uai.toJSON().toString()));
			bret = htu.send(syncapi.operation_type.regUser.urlpattern, 
					params, 
					pjson_resp);
		}
		if(bret)
		{
			iret = this.deal_realtime_request(pjson_resp.get());
		}			
		else
			iret = errMessage.err_sendtoservlet.errcode;		
		return iret;
	}

	@Override
	public int regVisitor() {
		// TODO Auto-generated method stub
		int iret= -1;
		boolean bret = true;
		List<NameValuePair> params = this.newparams();
		ClientDataRecord.user_auth_info uai = new ClientDataRecord.user_auth_info();
		wrapper<JSONObject> pjson_resp = new wrapper<JSONObject>(null);		
		if(bret)
		{
			ClientDataRecordBase cdrb = ldb.get_userRecord();
			if(cdrb != null)
			{
				ClientDataRecord.usersRecord ur = (ClientDataRecord.usersRecord) cdrb;
					
				uai.imei = HardwareHelper.getDM().getIMEI();
				uai.imsi = HardwareHelper.getDM().getIMSI();		
			
				params.add(new BasicNameValuePair(PostParam.p,ur.toJSON().toString()));
				params.add(new BasicNameValuePair(PostParam.user_auth_info_Param.record,uai.toJSON().toString()));
				bret = hu.send(syncapi.operation_type.regVisitor.urlpattern, 
						params, 
						pjson_resp);
			}
			
		}
		if(bret)
		{
			iret = this.deal_realtime_request(pjson_resp.get());
		}
		else
			iret = errMessage.err_sendtoservlet.errcode;		
		return iret;
	}
	
	private int addRecordbase(String url,ClientDataRecordBase crb,wrapper<ClientDataRecordBase> ret_crb)
	{
		int iret= -1;
		boolean bret = false;
		
		List<NameValuePair> params = this.newparams();		
		wrapper<JSONObject> pjsono_resp =  new 	wrapper<JSONObject>(null);
		params.add(new BasicNameValuePair(PostParam.p, crb.toString()));
		params.add(new BasicNameValuePair(PostParam.user_auth_info_Param.record, uai_Sing.get_uai().toJSON().toString()));
				
		bret = hu.send(url, params, pjsono_resp);
				//need deal with return value
		if(bret)
		{
			iret = this.dealwith_return(pjsono_resp.get(), ret_crb);
		}
		else
			iret = errMessage.err_sendtoservlet.errcode; 		
		
		return iret;
	}


	private int dealwith_return(JSONObject jsono, wrapper<ClientDataRecordBase> ret_crb)
	{
		int iret = -1;
		try {
			
			ClientDataRecordBase ret = ClientDataRecordBase.fromJSON(jsono);
			ret_crb.set(ret);
			if(ret == null)
				iret = -1;
			else
				iret = 0;
			if(iret >= 0)
			{
				ClientDataRecord.map_ClientDataRecord resp = (ClientDataRecord.map_ClientDataRecord) ret;
				if( resp.map.containsKey(tableName.t_return))
				{
					ClientDataRecordBase cdrb = resp.map.get(tableName.t_return);
					ClientDataRecord.returnValue r = (ClientDataRecord.returnValue) cdrb;
					iret = r.errcode;
				}
			}
			
			if(iret==errMessage.err_authenfail.errcode)
			{
				ldb.clearUserandvisitor();
				String imei = uai_Sing.get_uai().imei;
				String imsi = uai_Sing.get_uai().imsi;
				uai_Sing.init(-1, imsi, imei, -1, false);						
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			iret = errMessage.err_json.errcode;
		}
		return iret;
	}
	@Override
	public int syncWeibo(String username, String passwd) {
		int iret = -1;
        try {
        	System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
        	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
        	 Weibo weibo = new Weibo();        	 
             AccessToken accessToken = weibo.getXAuthAccessToken(username, passwd, "client_auth");
             if(accessToken != null)
             {
	             ClientDataRecord.weibocredential weiboc = new ClientDataRecord.weibocredential(accessToken.getToken(),accessToken.getTokenSecret());
	             JSONObject jsono = weiboc.toJSON();
	             String oa = null;
	             if(jsono!=null)
	            	 oa = jsono.toString();
	             ClientDataRecord.weiboRecord wr = new ClientDataRecord.weiboRecord(username, oa, NotedbHelper.nowTime());
	             iret = ldb.insertweiboitem(wr);	             
             }
             
		} catch (WeiboException e) {
			Log.i("synweibo error", e.getMessage());
			iret = -1;			
		}
		return iret; 
	}

	private int unbindbase(String uainame,String url)
	{
		int iret= -1;
		boolean bret = false;
		
		httpUtil htu = new httpUtil();
		bret = htu.init_mainthread();
		
		wrapper<JSONObject> pjsono_resp = new wrapper<JSONObject>(null);
		
		List<NameValuePair> params = this.newparams();		
			
		params.add(new BasicNameValuePair(uainame, uai_Sing.get_uai().toJSON().toString()));
		if(bret)
			bret = htu.send(url, params, pjsono_resp);
				//need deal with return value
		if(bret)
		{
			wrapper<ClientDataRecordBase> ret_crb = new wrapper<ClientDataRecordBase>(null);
			iret = this.dealwith_return(pjsono_resp.get(), ret_crb);
		}
		else
			iret = errMessage.err_sendtoservlet.errcode; 		
		
		return iret;
	}
	@Override
	public int unbindWeibo() {
		// TODO Auto-generated method stub
		int iret = 0;
		//delete weibo
		iret = ldb.deleteWeiboRecord();
		//send to server
		iret = this.unbindbase(PostParam.user_auth_info_Param.record, syncapi.operation_type.unbindweibo.urlpattern);
		return iret;
	}

	@Override
	public int logout() {
		// TODO Auto-generated method stub
		int iret = 0;
		iret = ldb.logoutUser();
		//delete user
		iret = this.unbindbase(PostParam.user_auth_info_Param.record, syncapi.operation_type.logout.urlpattern);
		return iret;
	}

	@Override
	public int getFoodUX(int food_id, List<Float> l, MinMax mm) {
		int iret = 0;
		uxRecord ur = ldb.get_food_ux(food_id);
		if(ur == null)
			iret = -1;
		else
		{
			l.addAll(ur.l);
			mm.min = ur.min;
			mm.max = ur.max;
		}
		return iret;
	}

	@Override
	public int getWeightUX(List<Float> l, MinMax mm) {
		int iret = 0;
		uxRecord ur = ldb.get_w_ux();
		if(ur == null)
			iret = -1;
		else
		{
			l.addAll(ur.l);
			mm.min = ur.min;
			mm.max = ur.max;
		}
		return iret;
	}

	@Override
	public int getHeightUX(List<Float> l, MinMax mm) {
		int iret = 0;
		uxRecord ur = ldb.get_h_ux();
		if(ur == null)
			iret = -1;
		else
		{
			l.addAll(ur.l);
			mm.min = ur.min;
			mm.max = ur.max;
		}
		return iret;
	}

	@Override
	public ClientDataRecord.usersRecord getuser() {
		// TODO Auto-generated method stub
		return ldb.get_userRecord();
	}
	
	public int getclientid()
	{
		return ldb.get_client_id();
	}

	@Override
	public int AddFeed(feedRecord fr) {
		// TODO Auto-generated method stub
		fr.r_date = StringUtil.onlyday(fr.r_time);
		fr.ts = StringUtil.now();
		fr.client_id = uai_Sing.get_uai().client_id;
		fr.mark = 1;
		return ldb.insertFeeds(fr);
	}

	@Override
	public int AddVisitor(int birth, boolean gender) {
		ClientDataRecord.usersRecord ur = new ClientDataRecord.usersRecord();
		ur.birth = birth;
		ur.gender = gender;
		ur.first_use_time = StringUtil.now();
		ur.first_use_time = 0;
		ur.isuser = false;
		ur.ts = StringUtil.now();
		ur.user_id =-1;
		ur.email = "";
		ur.passwd = "";
		return ldb.insertUser(ur);
		
	}

	@Override
	public int AddUser(int birth, boolean gender, String email, String password) {
		ClientDataRecord.usersRecord ur = new ClientDataRecord.usersRecord();
		ur.birth = birth;
		ur.gender = gender;
		ur.first_use_time = StringUtil.now();
		ur.first_reg_time = StringUtil.now();
		ur.isuser = false;
		ur.ts = StringUtil.now();
		ur.user_id =-1;
		ur.email = email;
		ur.passwd = password;
		return ldb.insertUser(ur);
	}

	@Override
	public int AddHUser(float height) {
		ClientDataRecord.hwUserRecord h = new ClientDataRecord.hwUserRecord(-1,height,0);
		h.client_id = uai_Sing.get_uai().client_id;
		h.ts = StringUtil.now();
		h.value = height;
		
		// TODO Auto-generated method stub
		return ldb.insertHUser(h);
	}

	@Override
	public int AddWUser(float weight) {
		ClientDataRecord.hwUserRecord h = new ClientDataRecord.hwUserRecord(-1,weight,0);
		h.client_id = uai_Sing.get_uai().client_id;
		h.ts = StringUtil.now();
		h.value = weight;
		
		// TODO Auto-generated method stub
		return ldb.insertWUser(h);
	}

	@Override
	public int AddFeedback(String content) {
		ClientDataRecord.feedbackRecord fr = new ClientDataRecord.feedbackRecord(-1, 0, content);
		fr.r_time = StringUtil.now();
		fr.ts = StringUtil.now();
		fr.user_id = uai_Sing.get_uai().id;
		
		return ldb.insertFeedback(fr);
	}

	@Override
	public int updateUserInfo(int birth, boolean gender) {
		ClientDataRecord.usersRecord ur = ldb.get_userRecord();
		ur.user_id = uai_Sing.get_uai().id;
		ur.birth = birth;
		ur.gender = gender;
		
		return ldb.updateUserInfo(ur);
		
	}

	@Override
	public List<contactRecord> getOurContact() {
		
		ClientDataRecord.list_ClientDataRecord lc = ldb.getContact(0);
		List<contactRecord> l = new ArrayList<contactRecord>();
		Iterator<ClientDataRecordBase> it = lc.list.iterator();
		while(it.hasNext())
		{
			ClientDataRecordBase crb = it.next();
			contactRecord cr = (contactRecord) crb;
			l.add(cr);
		}
		return l;
	}

	@Override
	public List<last_avgRecord> getAverage() {
		ClientDataRecord.list_ClientDataRecord lc = ldb.get_localavg(0);
		List<last_avgRecord> l = new ArrayList<last_avgRecord>();
		Iterator<ClientDataRecordBase> it = lc.list.iterator();
		while(it.hasNext())
		{
			ClientDataRecordBase crb = it.next();
			last_avgRecord cr = (last_avgRecord) crb;
			l.add(cr);
		}
		return l;
	}

	@Override
	public int getFoodPropid(String food_prop) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public weiboRecord getWeibo() {
		// TODO Auto-generated method stub
		return ldb.get_weibo();
	}

	@Override
	public List<ClientDataRecord.tipRecord> getTips() {
		// TODO Auto-generated method stub
		ClientDataRecordBase crb = ldb.get_tip();
		List<ClientDataRecord.tipRecord> l = new ArrayList<ClientDataRecord.tipRecord>();
		if(crb != null)
		{
			if(crb.get_type() == ClientDataRecordBase.ClientDataRecord_TYPE.tipRecord)
			{
				ClientDataRecord.tipRecord tr = (ClientDataRecord.tipRecord) crb;
				l.add(tr);
			}
			else
			{
				ClientDataRecord.list_ClientDataRecord lc = (ClientDataRecord.list_ClientDataRecord) crb;
				Iterator<ClientDataRecordBase> it = lc.list.iterator();
				while(it.hasNext())
				{
					ClientDataRecordBase c = it.next();
					tipRecord tr = (tipRecord) c;
					l.add(tr);
				}
			}
		}
		
		return l;
	}

	@Override
	public loadinfoRecord getLoadInfo() {
		// TODO Auto-generated method stub
		return ldb.get_loadinfo();
	}

	@Override
	public usersRecord getUser() {
		// TODO Auto-generated method stub
		return ldb.get_userRecord();
	}

	@Override
	public boolean getUserGender() {
		boolean gender = true;
		usersRecord ur = ldb.get_userRecord();
		if(ur != null)
		{
			gender = ur.gender;
		}
		return gender;
	}

	@Override
	public int getUserAge() {
		int iret = 0;
		usersRecord ur = ldb.get_userRecord();
		if(ur != null)
		{
			iret = StringUtil.getmonth(ur.birth);
		}
		return iret;
	}

	@Override
	public int getUserid() {
		int iret = -1;
		iret = uai_Sing.get_uai().id;
		return iret;
	}

	@Override
	public int getVisitorid() {
		int iret = -1;
		iret = uai_Sing.get_uai().id;
		return iret;
	}

	@Override
	public foodsRecord getFood(String foodname) {
		return this.getFood(foodname);
	}

	@Override
	public foodsRecord getFood(int food_id) {
		// TODO Auto-generated method stub
		return this.getFood(food_id);
	}

	@Override
	public hwAvgRecord getWeight(int age, boolean gender) {
		// TODO Auto-generated method stub
		return ldb.get_havg(age, gender);
	}

	@Override
	public hwAvgRecord getHeight(int age, boolean gender) {
		// TODO Auto-generated method stub
		return ldb.get_wavg(age, gender);
	}

	@Override
	public List<foodsRecord> getFoodybyCategory(String category) {
		ClientDataRecord.list_ClientDataRecord lc = ldb.getFoodybyCategory(category);
		return this.convert_foods(lc);
	}

	private List<foodsRecord> convert_foods(ClientDataRecord.list_ClientDataRecord lc)
	{
		List<foodsRecord> l = new ArrayList<foodsRecord>();
		Iterator<ClientDataRecordBase> it = lc.list.iterator();
		while(it.hasNext())
		{
			ClientDataRecordBase crb = it.next();
			foodsRecord cr = (foodsRecord) crb;
			l.add(cr);
		}
		return l;
	}
	private List<clientFeedRecord> convert_feeds(ClientDataRecord.list_ClientDataRecord lc)
	{
		List<clientFeedRecord> l = new ArrayList<clientFeedRecord>();
		Iterator<ClientDataRecordBase> it = lc.list.iterator();
		while(it.hasNext())
		{
			ClientDataRecordBase crb = it.next();
			clientFeedRecord cr = (clientFeedRecord) crb;
			l.add(cr);
		}
		return l;
	}
	@Override
	public List<foodsRecord> getFoodbyProp(int prop_id) {
		ClientDataRecord.list_ClientDataRecord lc = ldb.getFoodbyprop(prop_id);
		return this.convert_foods(lc);
	}

	@Override
	public List<clientFeedRecord> getSumFeeds(int date) {
		ClientDataRecord.list_ClientDataRecord lc = ldb.getSumFeeds(date);
		return this.convert_feeds(lc);
	}

	@Override
	public List<clientFeedRecord> getFeeds(int date) {
		ClientDataRecord.list_ClientDataRecord lc = ldb.getFeeds(date);
		return this.convert_feeds(lc);
	}

	@Override
	public uxRecord get_w_ux() {
		// TODO Auto-generated method stub
		return ldb.get_w_ux();
	}

	@Override
	public uxRecord get_h_ux() {
		// TODO Auto-generated method stub
		return ldb.get_h_ux();
	}

	@Override
	public uxRecord get_food_ux(int food_id) {
		// TODO Auto-generated method stub
		return ldb.get_food_ux(food_id);
	}

}
